﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Portal.Nhibernate.Repository;

namespace Portal.Web.Areas.Admin.Controllers
{
    public class AttachmentController : BaseAdminController
    {

        private readonly IAttachmentRepository<IAttachment> _attachmentRepository;

        public AttachmentController(IAttachmentRepository<IAttachment> attachmentRepository)
        {
            _attachmentRepository = attachmentRepository;
        }
        public AttachmentController()
        {
            _attachmentRepository = new AttachmentRepository();
        }



        public ActionResult Index()
        {
            _attachmentRepository.Get();
            return View();
        }

        public ActionResult GetAttachmentJson(string sort = "Sort", string order = "DESC", int page = 1, int rows = 10)
        {
            return Json(_attachmentRepository.Get().Sorting(sort, order).JqEasyuiDataGrid(page, rows));
        }
        public ActionResult Create()
        {
            var model = _attachmentRepository.CreateEntity();
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        [CacheResetFilterAttribute(CacheKey.AttachmentList)]
        public ActionResult Create(FormCollection formCollection, Attachment entity)
        {

            var model = _attachmentRepository.CreateEntity();
            model.Culture = Culture;
            model.Founder = CurrentUserName;
            _attachmentRepository.Add(model);
            _attachmentRepository.Save();
            ViewData["Result"] = new AjaxResult { message = "添加成功", state = false };
            return View(model);
        }



        public ActionResult Edit(string id)
        {
            var model = _attachmentRepository.Get().SingleOrDefault(o => o.Id == id);
            if (model == null)
                return NotFount(new AjaxResult { message = "没有找到记录", state = false });
            return View(model);
        }
        [HttpPost]
        [CacheResetFilterAttribute(CacheKey.AttachmentList)]
        public ActionResult Edit(Attachment entity)
        {
            var model = _attachmentRepository.Get().SingleOrDefault(o => o.Id == entity.Id);
            if (model == null)
                return NotFount(new AjaxResult { message = "没有找到记录", state = false });
            model.Culture = Culture;
            model.Founder = CurrentUserName;
            _attachmentRepository.Update(model);
            _attachmentRepository.Save();
            ViewData["Result"] = new AjaxResult { message = "修改成功", state = false };
            return View(model);
        }

        [HttpGet]
        public ActionResult UploadImage(Attachment entity)
        {
            var model = _attachmentRepository.CreateEntity();
            return View(model);
        }
        [HttpPost]
        public void UploadSave(Attachment entity, HttpPostedFileBase filedata, string path)
        {
            try
            {
                var upload = new UploadHelper(filedata, path) { };
                if (upload.Save())
                {
                    var model = _attachmentRepository.CreateEntity();
                    model.Culture = Culture;
                    model.Founder = CurrentUserName;
                    model.Url = upload.FileRelativePath;
                    model.BelongsType = entity.BelongsType;
                    model.BelongsId = entity.BelongsId;
                    _attachmentRepository.Add(model);
                    _attachmentRepository.Save();
                }
                ViewData["Result"] = new AjaxResult { message = "添加成功", state = false };
            }
            catch (Exception e)
            {
                Response.StatusCode = 500;
                Response.Write("An error occured");
                Response.End();
            }
            finally
            {
                Response.End();
            }
        }
        [HttpPost]
        public ActionResult UploadProductImage(Attachment entity, HttpPostedFileBase filedata, string path)
        {

            try
            {
                var upload = new UploadHelper(filedata, path) { IsImage = true, PicMaxLength = 1024 * 1000 };
                if (upload.Save())
                {

                    var thumpath =
                        upload.FileRelativePath.Insert(
                            upload.FileRelativePath.LastIndexOf("/", System.StringComparison.Ordinal) + 1, "jpeg-");
                    var xImage = new XImage();
                    xImage.ToThumbnail(upload.FileRelativePath, thumpath, 150, 150);

                    var model = _attachmentRepository.CreateEntity();
                    model.Culture = Culture;
                    model.Founder = CurrentUserName;

                    model.Url = upload.FileRelativePath;
                    model.BelongsType = entity.BelongsType;
                    model.BelongsId = entity.BelongsId;
                    _attachmentRepository.Add(model);

                    _attachmentRepository.Save();
                    return Json(new AjaxUploadImageResult { message = "上传成功", state = true, filename = upload.FileName, filerelativepath = upload.FileRelativePath, relativepath = upload.RelativePath, imageid = model.Id, thumimageid = model.Id, thumimagerelativepath = thumpath, thumbnailimagename = "jpeg-" + upload.FileName }, "text/html");

                }
                return Json(new AjaxUploadResult { message = "上传失败,{0}".FormatWith(upload.ErrorMessage), state = false }, "text/html");
            }
            catch (Exception e)
            {
                return Json(new AjaxUploadResult { message = "上传失败,{0}".FormatWith(e.Message), state = false }, "text/html");
            }

        }
        [HttpPost]
        [CacheResetFilterAttribute(CacheKey.AttachmentList)]
        public ActionResult DeleteProductImage(List<string> id, FormCollection collection)
        {
            var list = _attachmentRepository.Get().Where(o => id.Contains(o.Id)).ToList();
            FileHelper.DeleteSub(list.Select(o => Server.MapPath(o.Url)).ToArray());
            FileHelper.DeleteSub(list.Select(o => Server.MapPath(o.Url.NullSafe().Insert(o.Url.NullSafe().LastIndexOf("/", System.StringComparison.Ordinal) + 1, "jpeg-"))).ToArray());
            list.ForEach(o => _attachmentRepository.Delete(o));
            _attachmentRepository.Save();
            return Json(new AjaxResult { state = true, message = "删除成功" });
        }
        [HttpPost]
        public ActionResult UploadLinkImage(Attachment entity, HttpPostedFileBase filedata, string path)
        {

            try
            {
                var upload = new UploadHelper(filedata, path) { IsImage = true, PicMaxLength = 1024 * 1000 };
                if (upload.Save())
                {

                    var thumpath =
                        upload.FileRelativePath.Insert(
                            upload.FileRelativePath.LastIndexOf("/", System.StringComparison.Ordinal) + 1, "jpeg-");
                    var xImage = new XImage();
                    xImage.ToThumbnail(upload.FileRelativePath, thumpath, 150, 150);

                    var model = _attachmentRepository.CreateEntity();
                    model.Culture = Culture;
                    model.Founder = CurrentUserName;

                    model.Url = upload.FileRelativePath;
                    model.BelongsType = entity.BelongsType;
                    model.BelongsId = entity.BelongsId;
                    _attachmentRepository.Add(model);

                    _attachmentRepository.Save();
                    return Json(new AjaxUploadImageResult { message = "上传成功", state = true, filename = upload.FileName, filerelativepath = upload.FileRelativePath, relativepath = upload.RelativePath, imageid = model.Id, thumimageid = model.Id, thumimagerelativepath = thumpath, thumbnailimagename = "jpeg-" + upload.FileName }, "text/html");

                }
                return Json(new AjaxUploadResult { message = "上传失败,{0}".FormatWith(upload.ErrorMessage), state = false }, "text/html");
            }
            catch (Exception e)
            {
                return Json(new AjaxUploadResult { message = "上传失败,{0}".FormatWith(e.Message), state = false }, "text/html");
            }

        }
        [HttpPost]
        [CacheResetFilterAttribute(CacheKey.AttachmentList)]
        public ActionResult DeleteLinkImage(List<string> id, FormCollection collection)
        {
            var list = _attachmentRepository.Get().Where(o => id.Contains(o.Id)).ToList();
            FileHelper.DeleteSub(list.Select(o => Server.MapPath(o.Url)).ToArray());
            FileHelper.DeleteSub(list.Select(o => Server.MapPath(o.Url.NullSafe().Insert(o.Url.NullSafe().LastIndexOf("/", System.StringComparison.Ordinal) + 1, "jpeg-"))).ToArray());
            list.ForEach(o => _attachmentRepository.Delete(o));
            _attachmentRepository.Save();
            return Json(new AjaxResult { state = true, message = "删除成功" });
        }

        [HttpPost]
        [CacheResetFilterAttribute(CacheKey.AttachmentList)]
        public ActionResult Delete(List<string> id, FormCollection collection)
        {
            var list = _attachmentRepository.Get().Where(o => id.Contains(o.Id)).ToList();
            FileHelper.DeleteSub(list.Select(o => Server.MapPath(o.Url)).ToArray());
            list.ForEach(o => _attachmentRepository.Delete(o));
            _attachmentRepository.Save();
            return Json(new AjaxResult { state = true, message = "删除成功" });
        }
        [HttpPost]
        public void UploadImage()
        {
            try
            {
                string belongsId = Request.Form["belongsId"];
                string belongsType = Request.Form["belongsType"];
                HttpPostedFileBase filedata = Request.Files["Filedata"];
                string path = Request.Form["path"];
                var model = _attachmentRepository.CreateEntity();
                model.Culture = Culture;
                model.Founder = CurrentUserName;
                int b = 0;
                int.TryParse(belongsType, out b);
                model.BelongsType = b;
                model.BelongsId = belongsId;
                var upload = new UploadHelper(filedata, path) { IsImage = true, PicMaxLength = 1000 * 1024 };
                if (!upload.Save())
                {
                    TempData["Result"] = upload.ErrorMessage;
                    throw new Exception();
                }
                model.Title = upload.OriginalFileName;
                model.Descript = upload.OriginalFileName;
                model.Url = upload.FileRelativePath;
                _attachmentRepository.Add(model);
                _attachmentRepository.Save();
                ViewData["Result"] = new AjaxResult { message = "添加成功", state = true };
                Response.StatusCode = 200;
            }
            catch
            {
                // If any kind of error occurs return a 500 Internal Server error
                Response.StatusCode = 500;
                Response.Write("An error occured");
                Response.End();
            }
            finally
            {
                Response.End();
            }
        }
    }
}
